<template>
    <div class='image-container'>
    <el-card class="box-card">
        <div slot="header">
            <Breadcrumb>素材管理</Breadcrumb>
        </div>
        <div style="margin-bottom: 20px">
            <el-radio-group v-model="isCollected" size="small" @change="hCollected">
            <el-radio-button :label="false">全部</el-radio-button>
            <el-radio-button :label="true">收藏</el-radio-button>
            </el-radio-group>
            <el-button
            type="success"
            size="mini"
            style="float:right"
            @click="dialogVisible=true"
            >上传图片素材
            </el-button>
        </div>
        <el-row :gutter="10">
          <el-col :span="4" class="img_item" v-for="item in images" :key="item.id"><el-image
            style="height: 180px;width: 180px"
            :src="item.url"
            fit="cover">
            </el-image>
            <div class="option" v-show="!isCollected">
                <span class="el-icon-star-off" :class="{red: item.is_collected}" @click="hChangeImage(item)"></span>
                <span class="el-icon-delete" @click="hDelete(item.id)"></span>
            </div>
          </el-col>
        </el-row>
        <el-pagination
            style="margin-top:10px"
            background
            layout="prev, pager, next"
            @current-change="hCurrentchange"
            :total="total_count">
        </el-pagination>
    </el-card>

    <el-dialog title="上传素材"
    :append-to-body="true"
    :visible.sync="dialogVisible">
     <el-upload
      class="avatar-uploader"
      action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
      :headers="headers"
      name="image"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <el-image v-if="imageUrl" :src="imageUrl" class="avatar" @load='hloadImages'/>
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    </el-dialog>
    </div>
</template>
<script>
export default {
  name: 'ImageIndex',
  data () {
    return {
      curPage: 1,
      total_count: 0,
      isCollected: false,
      images: [],
      dialogVisible: false,
      imageUrl: '',
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    }
  },
  methods: {
    // 收藏和取消收藏功能
    async hChangeImage (item) {
      console.log(item)
      // 调用接口
      // const {'id': id, 'is_collected': isCollected} = item
      const { id, is_collected: isCollected } = item
      console.log(id, isCollected)
      try {
        const result = await this.$http({
          method: 'PUT',
          url: '/mp/v1_0/user/images/' + id,
          data: {
          // 切换是否收藏
            collect: !isCollected
          }
        })
        console.log(result)
        // 更新视图
        // 重新查询，需要多次调接口，费内存，不建议使用
        // this.LoadImages()
        // 直接修改数据
        item.is_collected = !isCollected
        this.$message.success('操作成功')
      } catch (err) {
        console.log(err)
        this.$message.success('操作失败')
      }
    },
    // 图片加载完后
    hloadImages () {
      console.log('hloadImages....')
      setTimeout(() => {
        this.imageUrl = ''
        this.dialogVisible = false
      }, 2000)
    },
    // 上传素材
    handleAvatarSuccess (res, file) {
      console.log(res)
      this.imageUrl = res.data.url
      this.$message.success('上传素材成功')
      this.LoadImages()
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 删除功能
    hDelete (id) {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        canceButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 获取数据id
        // 调接口删除数据
        try {
          const result = await this.$http({
            method: 'DELETE',
            url: '/mp/v1_0/user/images/' + id
          })
          console.log(result)
          // 重新获取一下页面
          this.LoadImages()
        } catch (err) {
          this.$message.error('删除失败')
        }
      }).catch(() => {
        // 用户取消了
      })
    },
    // 点击切换全部和收藏功能
    hCollected () {
      console.log(this.isCollected)
      this.curPage = 1
      this.LoadImages()
    },
    // 分页切换
    hCurrentchange (curPage) {
      console.log(curPage)
      this.curPage = curPage
      this.LoadImages()
    },
    async LoadImages () {
    // 通过接口获取素材列表
      const result = await this.$http({
        method: 'GET',
        url: '/mp/v1_0/user/images',
        params: {
          collect: this.isCollected,
          page: this.page
        }
      })
      console.log(result)
      this.images = result.data.data.results
      this.total_count = result.data.data.total_count
    }
  },
  created () {
    this.LoadImages()
  }
}
</script>
<style lang="less">
.image-container /deep/ .el-card__body{
  padding:30px;
}
// lang: 用来指定样式是用什么语言?(css, less, sass, scss....)
// scoped: 作用域。加这一项与不加这一样有极大的区别
//   - 如果加了，则下面样式是私有的
//   - 如果不加，则下面样式是全局的
.img_item {
  position: relative;
  box-sizing: border-box;
}
.option {
  position: absolute;
  left: 5px;
  width:180px;
  bottom: 5px;
  height: 30px;
  line-height: 30px;
  background: rgba(0, 0, 0, 0.3);
  text-align: center;
  color: #fff;
  span {
    margin: 0 30px;
    cursor: pointer;
  }
  .red{
    color: red;
  }
}
.avatar-uploader {
    text-align: center;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
</style>
